﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Cofe.Core;
using Cofe.Core.EntryType;
using Cofe.Core.Implements;
using Cofe.Core.Utils;
using Cofe.Web.Utils;

namespace Cofe.Web
{
    [Export(typeof(ICofeService))]
    [ServicePriority(ServicePriorityAttribute.DefaultPriority_COFEWS)]
    public class WSEntryXmlSerializer : EntryXmlSerializer
    {

        protected override object getValue(CofeSystemInfo entry, object prop)
        {
            switch ((int)prop)
            {
                case (int)CofeProperties.FullParseName:
                case (int)CofeProperties.ParentParseName:
                    return ((string)base.getValue(entry, prop)).Replace('\\', '/');
            }

            return base.getValue(entry, prop);
        }

        public override void WriteXml<T>(T entry, XmlWriter writer, bool includeDetails)
        {
            base.WriteXml<T>(entry, writer, includeDetails);
  
            writer.WriteStartElement(XNames.Links.LocalName);
            foreach (var l in UrlUtils.CreateLinks<T>(entry.Properties, null, includeDetails))
            {
                writer.WriteStartElement(XNames.Link.LocalName);

                writer.WriteAttributeString(XNames.MediaType.LocalName, l.MediaType.ToString());
                writer.WriteAttributeString(XNames.RelationType.LocalName, l.RelationType.ToString());
                writer.WriteAttributeString(XNames.Uri.LocalName, l.Uri.ToString().ToLower());

                writer.WriteEndElement();

            }
            writer.WriteEndElement();
        }

        public override void WriteObjectData<T>(T entry, SerializationInfo info, StreamingContext context, bool includeDetails = false)
        {
            base.WriteObjectData<T>(entry, info, context, includeDetails);
       
            IEnumerable<XmlLink> links = UrlUtils.CreateLinks<T>(entry.Properties, null,includeDetails);
                
            info.AddValue("links", links);
        }

        public override void WriteObjectData(IEnumerable<CofeSystemInfo> subEntries, ParameterDic pd, SerializationInfo info, StreamingContext context, bool IncludeDetails = false)
        {
            base.WriteObjectData(subEntries, pd, info, context, IncludeDetails);

            IEnumerable<XmlLink> links = UrlUtils.CreateParameterDicLinks(pd);
            if (links.Any())
                info.AddValue("links", links);

        }
    }
}
